package com.example.twotwo_project;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.example.twotwo_project.R.drawable;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class InputActivity extends ActionBarActivity {

	String[] address_list;
	String[] email_list;
	TextView tv;
	ImageView iv;
	Bitmap bm;
	
	// 데이터베이스
	String URL = "http://192.168.10.103:8888/Get2gether_Server/group/group_list.jsp";
	HttpClient client = new DefaultHttpClient();
	DBReader dbread;
	String temp = "";
	String[] data;
	
	// 임시 이미지 저장
	private static final String TEMP_PHOTO_FILE = "temp.jpg"; //임시 저장파일
	private static final int REQ_CODE_PICK_IMAGE = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_input);
		// 데이터베이스
		dbread = new DBReader();
		dbread.execute();
		
		
		getActionBar().setDisplayHomeAsUpEnabled(true);
		address_list = getResources().getStringArray(R.array.);
		email_list = getResources().getStringArray(R.array.email_list);
		Spinner sp1 = (Spinner)findViewById(R.id.spinner1);
		Spinner sp2 = (Spinner)findViewById(R.id.spinner2);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, address_list);
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, email_list);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp1.setAdapter(adapter);
		sp2.setAdapter(adapter2);
		
		sp1.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				TextView tv = (TextView)findViewById(R.id.textView8);
				tv.setText(address_list[position]);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		
		sp2.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				EditText et = (EditText)findViewById(R.id.editText7);
				et.setText(email_list[position]);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		
		
	}
	
	 public class DBReader extends AsyncTask<Void, String, Void>{

			@Override
			protected Void doInBackground(Void... params) {
				try{
					HttpGet get = new HttpGet(URL);// 필드에 정의된 URL주소를 가지고 와서 get에 삽입
					HttpResponse resp = client.execute(get);
					BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
					String str = null;
					StringBuilder sb = new StringBuilder();
					
					while((str = br.readLine()) != null){
						sb.append(str + "\n");
					}br.close();
					
					temp = sb.toString();
					temp = temp.trim(); // 불필요한 공백 제거 함수 trim();
					System.out.println("성공");
					
					data = temp.split("\n"); // 줄바꾸기 문자를 기준으로 문자열을 분리
					
				}catch(Exception ex){
					ex.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				EditText mid = (EditText)findViewById(R.id.editText1);
				EditText pwd = (EditText)findViewById(R.id.editText2);
				//EditText
				
				
			}
			
			
			
	    }
	
	
	
	public void btn_img(View v){
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, // 또는 ACTION_PICK 
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setType("image/*"); // 모든 이미지
		intent.putExtra("crop", "true"); // CROP 기능 활성화
		intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri()); // 임시파일 생성
		intent.putExtra("outputFormat", // 포맷방식 
				Bitmap.CompressFormat.JPEG.toString());
		startActivityForResult(intent, REQ_CODE_PICK_IMAGE);
		// REQ_CODE_PICK_IMAGE == requestCode
	}
	
	/*임시 저장 파일의 경로를 반환*/
	private Uri getTempUri(){
		return Uri.fromFile(getTempFile());
	}
	
	/*외장메모리에 임시 이미지 파일을 생성하여 그 파일의 경로를 반환*/
	private File getTempFile(){
		if(isSDCARDMOUNTED()){
			File f = new File(Environment.getExternalStorageDirectory(), // 외장메모리 경로 
					TEMP_PHOTO_FILE);
			try{
				f.createNewFile(); // 외장메모리에 temp.jpg 파일 생성
			}catch(Exception ex){
				
			}
			return f;
		}else{
			return null;
		}
	}
	
	private boolean isSDCARDMOUNTED(){
		String status = Environment.getExternalStorageState();
		if(status.equals(Environment.MEDIA_MOUNTED)) return true;
		
		return false;
	}
	
	



	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent Imagedata) {
		super.onActivityResult(requestCode, resultCode, Imagedata);
		
		switch(requestCode){
		case REQ_CODE_PICK_IMAGE:
			if(resultCode == RESULT_OK){
				if(Imagedata != null){
					String filePath = Environment.getExternalStorageDirectory() + "/temp.jpg";
					System.out.println("path" + filePath); // logcat으로 경로확인
					
					Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
					// temp.jpg파일을 Bitmap으로 디코딩한다.
					
					ImageView iv = (ImageView)findViewById(R.id.imageView1);
					iv.setImageBitmap(selectedImage); // temp.jpg파일을 이미지뷰에 씌운다.
				}
			}
			break;
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.input, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(android.view.MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml
		switch(item.getItemId()){
		case android.R.id.home:
			InputOut();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void InputOut(){
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("종료하시겠습니까?");
		dialog.setPositiveButton("예", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
				startActivity(intent);
			}
		});
		
		dialog.setNegativeButton("아니오", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(getApplicationContext(), "회원가입", Toast.LENGTH_SHORT).show();
			}
		});
		dialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch(keyCode){
		case KeyEvent.KEYCODE_BACK:
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setTitle("종료하시겠습니까?");
			dialog.setPositiveButton("예", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
					startActivity(intent);
				}
			});
			
			dialog.setNegativeButton("아니오", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(getApplicationContext(), "회원가입", Toast.LENGTH_SHORT).show();
				}
			});
			dialog.show();
			break;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	
	
}
